/* eslint-disable */
import { Button, Toast, Swiper, SwiperItem, Dialog } from "mand-mobile";
import store from "@/tools/factory"
import QrcodeDecoder from 'qrcode-decoder';
import { TMap } from "../../tools/Tmap";
import { config } from "@/api/config"
import * as Request from '@/api/liubike';
import tools from "@/tools/index";
import simple from 'mand-mobile/components/swiper/demo/data/simple'
let that = null;
// 计费轮询
let countTimer = null;
// 临时锁车轮询
let tempLockTimer = null;
// 临时开锁轮询
let tempUnlockTimer = null;
// 关锁轮询
let returnCarTimer = null;
// 计费计数
let countNum = 0;
// 关锁计数
let pollingCount = 0;

export default {
    name: "home",
    data() {
        return {
            isActive: 2,
            lat: config.latLng.lat,
            lng: config.latLng.lng,
            carInfoDialog: false,
            routerInfo: {},
            powerConfig: {
                chargeConfig: {},
                apmConfig: {}
            },
            haveCar: true,
            polygon: null,
            polygonPoints: [],
            parkList: [],
            carList: [],
            btnStatus: 0,
            outFence: false,
            bno: null,
            parkIcon: null,
            carIcon: null,
            unUsedCarIcon: null,
            simple,
            adList: [],
            adShow: true,
            orderInfo: {},
            riderShow: false,
            riderInfo: {
                showTxt: "正在获取"
            },
            hasUnpayOrder: false,
            returnCarStatus: false,
            currentCarInfo: {},
            parkingImg: null,
            payHelmetFee: null,
            phoneAngle: null,
            tabSelectClick: true,
            findBellbuttonClick: false
        };
    },
    components: {
        [Button.name]: Button,
        [Toast.name]: Toast,
        [Swiper.name]: Swiper,
        [SwiperItem.name]: SwiperItem
    },
    methods: {
        tabSelect(type) {
            this.isActive = type;
            this.carInfoDialog = false
            this.initMarker()
        },
        bannerClickEvent(link) {
            if (!link) {
                return false
            }
            store.set("wxWeb", link);
            this.$router.push({
                name: "webview"
            })
        },
        rideServiceStatus(operatestatus) { // 车辆是否可用显示状态
            /**
             * @param  {[Object]} data [必填, 车辆完整信息]
             * @return {[Boolean]} [true-可用, false-不可用]
             */
            if (!data) {
                return false
            };
            // 已预约
            if (operatestatus === 1) {
                return false;
            }
            // 可用故障车
            if (operatestatus === 7) {
                return false;
            }
            // 不可用故障车
            if (operatestatus === 8) {
                return false;
            }
            // 使用中
            if (operatestatus === 2) {
                return false;
            }
            // 空闲可用车辆
            return true;
        },
        goUserCenter() {
            this.$router.push({
                name: "userCenter"
            })
        },
        clearEvent() {
            countNum = 0;
            clearInterval(countTimer);
            clearInterval(tempLockTimer);
            clearInterval(tempUnlockTimer);
            clearInterval(returnCarTimer);
        },
        queryCar(event, fn) {
            Request.getVehicle({
                customNo: this.bno,
                outFence: that.routerInfo.outFence,
                event: event || "other"
            }).then(res => {
                fn && fn(res)
            })
        },
        getBannerInfo() {
            Request.getBannerInfo({ areaId: this.routerInfo.areaId }).then(res => {
                if (res.success) {
                }
            })
        },
        goPayOrder() {
            this.$router.push({
                name: "payOrder"
            })
        },
        getHasUnsettlementOrder() {
            Request.getHasUnsettlementOrder().then(res => {
                if (res.success) {
                    that.hasUnpayOrder = res.data.hasUnsettlementOrder;
                } else {
                    that.hasUnpayOrder = false;
                }
            })
        },
        getAd() {
            Request.getAdTips({
                lat: this.lat, lng: this.lng
            }).then(res => {
                if (res.success) {
                    that.adList = res.data;
                    if (that.adList && that.adList.length > 0 && Object.keys(that.orderInfo).length === 0) {
                        that.adShow = true
                    } else {
                        that.adShow = false
                    }
                }
            })
        },
        closeModel() {
            this.adShow = false
        },
        drawFence() {
            let path = [];
            if (this.routerInfo.polygonPonits == this.polygonPoints) {
                return false
            }
            this.polygonPoints = this.routerInfo.polygonPonits
            if (!this.polygonPoints || this.polygonPoints.length == 0) {
                return false
            }
            if (this.polygon) {
                this.polygon.setMap(null);
            }
            this.polygonPoints.map(item => {
                path.push(new qq.maps.LatLng(item.lat, item.lng))
            })
            path.push(new qq.maps.LatLng(that.polygonPoints[0].lat, that.polygonPoints[0].lng))
            //初始化polygon
            this.polygon = new qq.maps.Polygon({
                //多边形的填充色，可通过Color对象的alpha属性设置透明度。
                fillColor: new qq.maps.Color(0, 0, 0, 0),
                //fillColor: new qq.maps.Color(0, 0, 0, 0.5),
                //要显示多边形的地图。
                map: that.map,
                //多边形的路径，以经纬度坐标数组构成。
                path: path,
                //多边形的线条颜色，可通过Color对象的alpha属性设置透明度。
                strokeColor: '#ff6e2a',
                //多边形的边框样式。实线是solid，虚线是dash。
                strokeDashStyle: 'dash',
                //多边形的边框线宽。
                strokeWeight: 5,
                //多边形是否可见。
                visible: true,
                //多边形的zIndex值。
                zIndex: 1000
            });
        },
        getVehicleList() {
            Request.getApiVhicle({
                lat: this.lat,
                lng: this.lng,
                coord: 0
            }).then(res => {
                that.tabSelectClick = true
                if (that.carList.length > 0) {
                    that.carList.map(item => {
                        item.setMap(null)
                    })
                }
                if (!res) {
                    return false
                }
                if (res.length == 0) {
                    that.haveCar = false
                    return false
                }
                that.haveCar = true
                res.map(item => {
                    //创建一个Marker
                    let marker = new qq.maps.Marker({
                        position: new qq.maps.LatLng(item.coordinate.lat, item.coordinate.lng),
                        map: that.map,
                        icon: that.rideServiceStatus(item.operatestatus) ? that.carIcon : that.unUsedCarIcon,
                        distance: item.distance,
                        mileage: item.mileage,
                        operatorNo: item.operatorNo,
                        operatestatus: item.operatestatus,
                        customno: item.customno
                    });
                    qq.maps.event.addListener(marker, 'click', function () {
                        that.carInfoDialog = true
                        that.currentCarInfo = {
                            distance: marker.distance,
                            mileage: marker.mileage,
                            operatorNo: marker.operatorNo,
                            customno: marker.customno
                        }
                        console.log(that.currentCarInfo)
                    })
                    that.carList.push(marker)
                })
            }).catch(err => {
                that.tabSelectClick = true
            })
        },
        getParkingSpot() {
            Request.getParkingspot({
                lat: this.lat,
                lng: this.lng,
                coord: 0,
            }).then(res => {
                that.tabSelectClick = true;
                if (that.parkList.length > 0) {
                    that.parkList.map(item => {
                        item.setMap(null);
                    })
                    that.parkList = [];
                }
                //添加标记
                if (res.length == 0) {
                    return false
                }
                res.map(item => {
                    //创建一个Marker
                    let marker = new qq.maps.Marker({
                        position: new qq.maps.LatLng(item.coordinate.lat, item.coordinate.lng),
                        map: that.map,
                        icon: that.parkIcon
                    });
                    qq.maps.event.addListener(marker, 'click', function () {
                    })
                    that.parkList.push(marker)
                })
            }).catch(err => {
                that.tabSelectClick = true;
            })
        },
        scan() {
            this.$refs.filElem.dispatchEvent(new MouseEvent('click'))
        },
        getUrl(type) {
            let elem = document.getElementById('file');
            let qr = new QrcodeDecoder();
            let url = null;
            if (type === 'img-url') {
                url = elem.src;
            } else if (type === 'file-url' && elem.files.length > 0) {
                url = tools.getObjectURL(elem.files[0]);
            }
            qr.decodeFromImage(url).then((res) => {
                let options = tools.getOptions(res.data);
                that.bno = options['bno'];
                that.queryCar("scan", res => {
                    store.set("carInfo", res);
                    that.$router.push({ name: 'readyUnlock' })
                })
            });
        },
        initData() {
            that.clearEvent()
            if (store.get("token")) {
                that.getUserOrder(function () {
                    that.getBannerInfo();
                    that.getAd();
                    that.getHasUnsettlementOrder()
                }, function () {
                    that.getBannerInfo();
                    that.getAd();
                });
            }
            that.getPowerConfig();
        },
        getUserOrder(fn, errFn) {
            Request.getUserOrder().then(res => {
                if (res.success) {
                    that.orderInfo = res.data;
                    that.bno = res.data.customNo;
                    that.riderShow = true;
                    store.set("orderInfo", res.data);
                    // 骑行订单计时及计费
                    that.orderHandle()
                } else {
                    that.riderShow = false;
                    if (store.get("orderInfo")) {
                        store.remove("orderInfo");
                        that.updateCurrentRidingState();
                    }
                    fn && fn();
                }
            }).catch(err => {
                errFn && errFn()
            })
        },
        orderHandle() {
            let orderInfo = that.orderInfo || store.get("orderInfo");
            let timeStamp = orderInfo.time / 60 / 1000; // 订单时间戳
            let TIME = (Math.round(timeStamp * 10) / 10).toFixed(1); // 已使用时间(分,秒)
            let MIN = parseInt(TIME); // 分
            let SEC = parseInt(parseFloat(TIME.toString().split(".")[1]) * 60 / 10); // 四舍五入已使用的时间(秒)
            let timeInfo = {
                time: TIME,
                min: MIN,
                sec: SEC
            }
            that.queryCar("other", res => {
                that.riderInfo = res;
                if (res.operatestatus == 2 || res.operatestatus == 0) {
                    that.riderInfo.vehicleStatus = "driving"
                } else {
                    that.riderInfo.vehicleStatus = "locking"
                }
                // 骑行订单计时及计费
                that.charging(timeInfo);
            })
        },
        charging(timeInfo) {
            if (!timeInfo) return;
            let sec = timeInfo.sec || 0;
            let minute = timeInfo.min || 0; // 计时60s
            let monetary = 0; // 消费金额
            let showTxt = "";
            if (sec || minute) {
                countNum = (minute * 60 + sec);
            } else {
                countNum = 0
            }
            let config = that.powerConfig;
            let vehicleState = that.orderInfo.arrearsState;
            clearInterval(countTimer);
            // 每秒更新一下骑行信息
            countTimer = setInterval(() => {
                sec += 1;
                countNum += 1;
                if (sec === 60) {
                    minute += 1;
                    sec = 0;
                }
                if (config) {
                    if (vehicleState == 1) {
                        showTxt = config.ridingTextConfig.powerOffNoticeText
                    } else if (vehicleState == 2) {
                        showTxt = config.ridingTextConfig.powerOffLimitText
                    } else {
                        if (config.chargeConfig) {
                            if (parseInt(minute * 60 + sec) > config.chargeConfig.freeTime) {
                                showTxt = config.ridingTextConfig.defaultRidingText
                            } else {
                                showTxt = config.ridingTextConfig.ridingStartText
                            }
                        }
                        if (that.routerInfo.outFence) {
                            showTxt = config.ridingTextConfig.outFenceRidingText;
                        }
                    }
                }
                // 按时间收费
                monetary = tools.getOrderMoneyByTime(minute * 60 + sec, that.powerConfig.chargeConfig);
                that.$set(that.riderInfo, "cost", monetary);
                that.$set(that.riderInfo, "serviceTime", `${tools.zeroPadding(minute)} : ${tools.zeroPadding(sec)}`);
                that.$set(that.riderInfo, "sec", `${tools.zeroPadding(sec)}`);
                that.$set(that.riderInfo, "min", `${tools.zeroPadding(minute)}`);
                that.$set(that.riderInfo, "showTxt", showTxt);
            }, 1000);
        },
        tempUnlock() {
            Toast.loading("开锁中...")
            Request.tempUnlockCar({
                operatorNo: this.riderInfo.operatorNo || null,
                source: 2,
                lock: false,
                temp: true,
                lng: this.lng,
                lat: this.lat
            }).then(res => {
                if (res.success) {
                    clearInterval(tempUnlockTimer);
                    that.tempSuccessHandle(tempUnlockTimer, 2)
                } else {
                    that.handleTempEvent(res)
                }
            })
        },
        tempLockClickEvent() {
            Dialog.confirm({
                title: '临时锁车',
                content: '临时锁车将持续计费',
                confirmText: '临时锁车',
                onConfirm: function () {
                    that.tempLock()
                },
            })
        },
        tempUnlockClickEvent() {
            that.tempUnlock();
        },
        tempSuccessHandle(timer, type) {
            let timesRun = 0;
            clearInterval(timer);
            timer = setInterval(function () {
                timesRun += 1; //每刷新一次 timesRun 就+1
                if (timesRun === 8) { //如果它等于 8 次了，就删除这个 setInterval 循环
                    Toast.hide();
                    clearInterval(timer);
                    if (type == 3) {
                        Toast.failed("临时锁车失败请重试")
                    }
                    if (type == 2) {
                        Toast.failed("开锁失败请重试")
                    }
                    return false
                }
                that.getVehiclePoll(type, timer)
            }, 2000);
        },
        tempLock() {
            Toast.loading("临时锁车中...")
            Request.tempLockCar({
                lock: true,
                operatorNo: this.riderInfo.operatorNo || null,
                source: 2,
                temp: true,
                tempCheck: false,
                lng: this.lng,
                lat: this.lat
            }).then(res => {
                if (res.success) {
                    clearInterval(tempLockTimer);
                    that.tempSuccessHandle(tempLockTimer, 3)
                } else {
                    //处理临时锁车失败的情况
                    that.handleTempEvent(res)
                }
            })
        },
        returnCar() {
            if (pollingCount > 10) {
                that.initReturnCarStatus();
            }
            Toast.loading("还车中...");
            Request.lockCar({
                operatorNo: this.riderInfo.operatorNo || null,
                lock: true,
                temp: false,
                source: 2, // 开锁来源 => 0 - Android, 1 - iOS, 2 - 小程序
                lat: this.lat || 0,
                lng: this.lng || 0,
                outFence: this.routerInfo.outFence,
                payHelmetFee: this.payHelmetFee ? true : false,
                parkingImg: this.parkingImg ? this.parkingImg : "",
                phoneAngle: this.phoneAngle ? this.phoneAngle : ""
            }).then(res => {
                console.log(res);
                pollingCount = 0;
                Toast.hide();
                if (res.success) {
                    if (!res.data) {
                        that.stopAddMoney(-1);
                        return false
                    }
                    let returnTime = res.data.ridingMillisecond || 0;
                    let time = Math.floor(returnTime / 1000 - countNum);
                    that.stopAddMoney(time);
                } else {
                    Dialog.alert({
                        title: '温馨提示',
                        content: res.msg,
                        confirmText: '我知道了',
                        onConfirm: function () {
                            if (res.data.errCode == "011") {
                                that.$router.push({
                                    name: "bill",
                                    query: {
                                        orderNo: that.orderInfo.orderNo
                                    }
                                })
                                return false
                            }
                        }
                    })
                }
            })
        },
        stopAddMoney(time) {
            Toast.loading("停止计费...");
            pollingCount = 0;
            clearInterval(returnCarTimer);
            returnCarTimer = setInterval(function () {
                pollingCount += 1; //每刷新一次 timesRun 就+1
                if (pollingCount === 10) { //如果它等于 8 次了，就删除这个 setInterval 循环
                    Dialog.alert({
                        title: '还车失败',
                        content: '请稍候再试',
                        confirmText: '我知道了'
                    })
                    that.initReturnCarStatus()
                    return false
                }
                that.returnCarByOrder()
            }, 2000);
        },
        returnCarByOrder() {
            Request.getUserOrder().then(res => {
                if (!res.success) {
                    that.updateCurrentRidingState();
                    if (that.orderInfo.quickPay) {
                        that.$router.push({
                            name: "bill",
                            query: {
                                orderNo: that.orderInfo.orderNo
                            }
                        })
                    } else {
                        Request.orderIsPaid({
                            orderNo: that.orderInfo.orderNo
                        }).then(res => {
                            if (res.success && res.data && res.data.isPaid) {
                                that.$router.push({
                                    name: "bill",
                                    query: {
                                        orderNo: that.orderInfo.orderNo
                                    }
                                })
                            } else {
                                store.set("pageSource", "RIDING_END")
                                that.$router.push({
                                    name: "payOrder"
                                })
                            }
                        }).catch(err => {
                            store.set("pageSource", "RIDING_END")
                            that.$router.push({
                                name: "payOrder"
                            })
                        })
                    }
                }
            })
        },
        initReturnCarStatus() {
            Toast.hide();
            pollingCount = 0;
            clearInterval(returnCarTimer);
            that.returnCarStatus = false
        },
        returnCarClickEvent() {
            if (returnCarTimer) {
                clearInterval(returnCarTimer);
            }
            if (this.returnCarStatus) {
                Toast.failed("请勿频繁点击")
                return false
            }
            this.returnCarStatus = true;
            that.returnCar();
        },
        handleTempEvent(res) {
            let req = res.data;
            Toast.hide();
            Dialog.alert({
                title: '温馨提示',
                content: res.msg,
                confirmText: '我知道了',
                onConfirm: function () {
                    if (req.errCode == "011") {
                        that.initData();
                        return false
                    }
                }
            })
        },
        reserve() {
            Dialog.alert({
                title: '温馨提示',
                content: "暂不支持预约用车",
                confirmText: '我知道了',
                onConfirm: function () {
                }
            })
        },
        getVehiclePoll(status, timer) {
            Request.getUserOrder().then(res => {
                if (res.success) {
                    let req = res.data;
                    if (req.vehicleBikeState == 3 && status == 3) {
                        that.clearVehiclePoll(timer);
                        Dialog.alert({
                            title: '温馨提示',
                            content: "临时锁车失败，请重试",
                            confirmText: '我知道了',
                            onConfirm: function () {
                            }
                        })
                        return false
                    }
                    if (status == 2) {
                        if (!req.lock) {
                            that.clearVehiclePoll(timer);
                            Toast.succeed("开锁成功");
                            that.riderInfo.vehicleStatus = "driving"
                        }
                    } else {
                        if (req.lock) {
                            that.clearVehiclePoll(timer);
                            Toast.succeed("临时锁车成功");
                            that.riderInfo.vehicleStatus = "locking"
                        }
                    }
                }
            })
        },
        clearVehiclePoll(timer) {
            clearInterval(timer);
            timer = null;
            Toast.hide()
        },
        getPowerConfig() {
            Request.getPowerConfig().then(res => {
                if (res.success) {
                    let req = res.data;
                    if (req) {
                        that.powerConfig = req;
                        store.set("powerConfig", req);
                    }
                } else {
                    Toast.info(res.msg)
                }
            })
        },
        updateCurrentRidingState() {
            that.initReturnCarStatus()
            Toast.succeed("还车成功!")
            this.riderInfo = {};
            this.orderInfo = {};
            this.riderShow = false
        },
        getRouter(fn, errFn) {
            Request.getRouter({
                lat: this.lat,
                lng: this.lng,
                relocated: false
            }).then(res => {
                that.routerInfo = {
                    bikeBaseUrl: res.data || "",
                    polygonPonits: res.point || "",
                    areaId: res.areaid || "",
                    cityRegion: res.cityRegion || "",
                    outFence: res.success,
                    wsUrl: res.wsUrl || "",
                    userRouter: res.userRouter || ""
                };
                store.set("routerInfo", that.routerInfo)
                if (res.success) {
                    fn && fn()
                } else {
                    errFn && errFn()
                }
            })
        },
        initMarker() {
            if (that.parkList.length > 0) {
                that.parkList.map(item => {
                    item.setMap(null)
                })
                that.parkList = []
            }
            if (that.carList.length > 0) {
                that.carList.map(item => {
                    item.setMap(null)
                })
                that.carList = []
            }
            this.getRouter(function () {
                that.drawFence();
                that.tabSelectClick = false
                if (that.isActive == 1) {
                    that.getVehicleList();
                } else {
                    that.haveCar = true
                    that.getParkingSpot();
                }
            })
        },
        unlockCar() {
            console.log("111")
            store.set("carInfo", this.currentCarInfo);
            this.$router.push({ name: 'readyUnlock' })
        },
        findBell() { // 寻车铃
            this.findBellbuttonClick = true
            setTimeout(function () {
                that.findBellbuttonClick = false
            }, 5000)
            const OPERATORNO = this.currentCarInfo.operatorNo
            // 登录后可使用停车铃
            Request.findTheCar({
                bell: true,
                operatorNo: OPERATORNO
            }).then(res => {
                if (!res.success) {
                    Dialog.alert({
                        title: '温馨提示',
                        content: res.msg,
                        confirmText: '确定',
                        onConfirm: function () {
                        }
                    })
                }
            });
        },
        markerStyle() {
            // 车辆图标
            let carAnchor = new qq.maps.Point(0, 22),
                carSize = new qq.maps.Size(38, 44),
                carOrigin = new qq.maps.Point(0, 0),
                carScaleSize = new qq.maps.Size(38, 44),
                carIcon = new qq.maps.MarkerImage(
                    require("../../images/available@2x4.png"),
                    carSize,
                    carOrigin,
                    carAnchor,
                    carScaleSize
                );
            let unUsedCarIcon = new qq.maps.MarkerImage(
                require("../../images/unavailable@3x.png"),
                carSize,
                carOrigin,
                carAnchor,
                carScaleSize
            );
            this.carIcon = carIcon;
            this.unUsedCarIcon = unUsedCarIcon;
            // 停车点图标
            let anchorB = new qq.maps.Point(0, 25),
                sizeB = new qq.maps.Size(35, 51),
                originB = new qq.maps.Point(0, 0),
                scaleSizeB = new qq.maps.Size(35, 51),
                iconB = new qq.maps.MarkerImage(
                    require("../../images/icon_parking_spot@2x.png"),
                    sizeB,
                    originB,
                    anchorB,
                    scaleSizeB
                );
            this.parkIcon = iconB;
        },
        setCenter() {
            this.map.setCenter(new qq.maps.LatLng(config.latLng.lat, config.latLng.lng));
            this.lat = config.latLng.lat;
            this.lng = config.latLng.lng;
            this.initMarker()
        },
        initMap() {
            //定义地图中心点坐标
            TMap().then(qq => {
                let center = new qq.maps.LatLng(config.latLng.lat, config.latLng.lng);
                store.set("lat", config.latLng.lat);
                store.set("lng", config.latLng.lng);
                that.map = new qq.maps.Map(document.getElementById("container"), {
                    // 地图的中心地理坐标。
                    center: center,
                    zoom: 16,
                    mapTypeControl: false,
                    panControl: false,
                    zoomControl: false,
                    scaleControl: false
                });
                // 重置所有marker
                that.markerStyle();
                that.initMarker();
                that.initData();
                qq.maps.event.addListener(that.map, 'dragend', function () {
                    let latLng = that.map.getCenter();
                    that.lat = latLng.lat;
                    that.lng = latLng.lng;
                    // 重置所有marker
                    that.initMarker();
                });

                //当可视区域范围更改时会触发此事件。返回当前地图的视野范围。
                qq.maps.event.addListener(that.map, 'click', function () {
                    that.carInfoDialog = false
                });
            });
        },
    },
    created() {
        this.initMap();
        if (store.get("token")) {
            this.btnStatus = 1
        } else {
            this.btnStatus = 0
        }
        console.log(store.get("token"))
    },
    mounted() {
        that = this;
        that.tabSelectClick = true
    }
};